import { Loading } from 'element-ui'
import * as _ from 'lodash'
import html2docx from 'html-docx-js/dist/html-docx.js'

export const exportHtmlToDocx = (content: HTMLDocument) => {
  const page = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' + content + '</body></html>'
  const Blob = html2docx.asBlob(page)
  return Blob
}

export const throttle = (wait: number, options = {}) => {
  return (target: any, name: string, descriptor: any) => {
    descriptor.value = _.throttle(descriptor.value, wait, options)
  }
}

export const debounce = (wait: number, options = {}) => {
  return (t: any, name: string, descriptor: any) => {
    descriptor.value = _.debounce(descriptor.value, wait, options)
  }
}

export const uuid = (len: number, radix: number) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  const uuidResult = [];
  let i;
  const tempRadix = radix || chars.length;

  if (len) {
    for (i = 0; i < len; i++) {
      // tslint:disable-next-line: no-bitwise
      uuidResult[i] = chars[0 | Math.random() * tempRadix];
    }
  } else {
    let r;
    uuidResult[8] = uuidResult[13] = uuidResult[18] = uuidResult[23] = '-';
    uuidResult[14] = '4';
    for (i = 0; i < 36; i++) {
      if (!uuidResult[i]) {
        // tslint:disable-next-line: no-bitwise
        r = 0 | Math.random() * 16;
        // tslint:disable-next-line: no-bitwise
        uuidResult[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuidResult.join('');
}

/**
 * loading 装饰器
 * @param {*} message 提示信息
 * @param {function} errorFn 异常处理逻辑
 */
export const loading = (message: string = 'loading...', errorFn?: any) => {
  return (target: any, name: string, descriptor: any) => {
    const fn = descriptor.value
    descriptor.value = async function(...rest: any) {
      const loadingMask = Loading.service({
        lock: true,
        text: message,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, .5)',
      })
      try {
        return await fn.call(this, ...rest)
      } catch (err) {
        if (errorFn) {
          errorFn.call(this, ...rest)
        }
      } finally {
        loadingMask.close()
      }
    }
  }
}

export const getAvatar = (fileName: string = '') => {
  const defaultAvatar = require('../assets/images/default-avatar.jpeg')
  if (!fileName) return defaultAvatar
  let avatar: string = ''
  try {
    avatar = require('../assets/images/' + fileName)
  } catch {
    avatar = defaultAvatar
  }
  return avatar
}